<!--  -->
<template>
  <div>
        <Card>
            <div slot="title" >
                <Button v-if="btnp.banner_xz" @click="handleAddbanner" class="zh-hollow" type="primary" icon="plus-round">新增Banner</Button>
            </div>
            <Table :loading="loading" border :columns="columns" :data="data"></Table>
            <Page :current.sync="pageNumber" :total="total" show-total show-sizer @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
        </Card>  
        <Modal :title="addBanner.title" v-model="modal_banner"  :mask-closable="false" class="zh-modal-form" >
            <div style="padding:15px 30px;">
                <Form :model="addBanner" :label-width="80">
                    <FormItem label="Banner名称*">
                        <Input v-model="addBanner.name" clearable></Input>
                    </FormItem>
                    <FormItem label="链接地址*">
                        <Input v-model="addBanner.link" clearable></Input>
                    </FormItem>  
                    <FormItem label="图片*">
                        <template v-if="!!addBanner.bannerImg.url">
                            <div class="upload-wrap" v-if="addBanner.bannerImg.status === 'finished'" style="display:block;width:375px;height:115px;">
                                <img :src="addBanner.bannerImg.url" style="display:block;width:375px;height:115px;">
                                <div class="upload-cover" style="width:375px;height:115px;">
                                    <div class="iconBox">
                                        <Icon type="ios-eye-outline" @click.native="handleView(addBanner.bannerImg.url)"></Icon>
                                        <Icon type="ios-trash-outline" @click.native="handleRemove(addBanner.bannerImg.url)"></Icon>
                                    </div> 
                                    
                                </div>
                            </div>
                            <template v-else>
                                <Progress v-if="addBanner.bannerImg.showProgress" :percent="addBanner.bannerImg.percentage" hide-info></Progress>
                            </template>
                        </template>
                        <template v-else>
                            <Upload
                                ref="upload"
                                multiple
                                :default-file-list="defaultList"
                                :show-upload-list="false"
                                :on-success="handleSuccess"
                                :format="['jpg','jpeg','png']"
                                :max-size="2048"
                                :on-format-error="handleFormatError"
                                :on-exceeded-size="handleMaxSize"
                                :before-upload="handleBeforeUpload"
                                type="drag"
                                :data="upLoadData"
                                action=" http://upload.qiniup.com"
                                style="display: inline-block;width:375px;height:115px;">
                                <div style="width:375px;height:115px;line-height: 115px;">
                                    <Icon type="ios-plus-empty" :size='40'></Icon>
                                </div>
                            </Upload>
                            <p>请上传jpg/png格式，小于2M的图片，建议尺寸为750px*230px</p>
                        </template>
                        
                    </FormItem>   
                </Form>
            </div>
            <div slot="footer">
                <div class="zh-flex zh-flex-5" >
                    <Button @click="modal_banner=false;" type="ghost">放弃操作</Button>
                    <Button @click="saveForm" class="zh-hollow" type="primary" >保存</Button>
                </div> 
            </div>
        </Modal>
        <Modal title="查看Banner" v-model="look_pic_wrap.look_pic" class="no_footer_modal">
            <img style="width:100%;" :src="look_pic_wrap.src" alt="">
        </Modal>   
    </div> 
  </template>


<script>
import util from '@/libs/util.js'
import * as qiniu from 'qiniu-js'
import {getBannerList,editBanner,getQiniuToken} from '@/libs/get.js'
import {saveBanner} from '@/libs/post.js'
export default {
    name:'banner',
    data () {
        return {
            btnp:{},
            btn:{
                banner_xz:false,
                banner_ck:false,
                banner_bj:false
            },
            upLoadData:{
                token:'',
                unique_names: true,
                domain:this.$store.state.app.domain
            },
            defaultList:[],
            canclick:true,
            pageSize:10,
            pageNumber:1,
            domain:this.$store.state.app.domain,
            total:0,
            look_pic_wrap:{
                look_pic:false,
                src:''
            },
            uploadList:[],
            loading:true,
            modal_banner:false,
            addBanner:{
                uuid:'',
                title:'',
                name:'',
                link:'',
                src:'',
                bannerImg:{
                    name:'',
                    url:'',
                    status:'',
                    showProgress:true,
                    percentage:0
                }
            },
            columns:[
                {
                    key:'bannerName',
                    title:'Banner名称'
                },
                {
                    key:'addTime',
                    title:'新增时间'
                },
                {
                    key:'action',
                    title:'操作',
                    align:'center',
                    render:(h,params)=>{
                        let uuid=params.row.uuid;
                         return h('div',[
                             h('Button',{
                                props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#2D8CF0',
                                display:this.btnp.banner_bj?'inline-block':'none'
                                },
                                
                            },[h('a',{
                                attrs:{
                                    href:params.row.url,
                                    target:'_blank'
                                }  
                            },'查看')]),
                            
                            h('Button',{
                                props:{
                                type:'text',
                                size:'small'
                                
                                },
                                style:{
                                color:'#2D8CF0',
                                display:this.btnp.banner_bj?'inline-block':'none'
                                },
                                on:{
                                    click:()=>{
                                        this.goedit(params.row);
                                    }
                                }
                            },'编辑'),
                         ])
                    }
                }
            ],
            data:[]
        };
    },
    methods:{
        async qiniuToken(){
            let res=await getQiniuToken();
            let response=res.data;
            if(response.code===200){
                this.upLoadData.token=JSON.parse(response.data).uptoken;
            }else{
                this.$Notice.error({
                    title: '请求出错',
                    desc:response.msg
                });
                return false
            }
        },
        async getTable(){
            this.loading=true;
            let res=await getBannerList(this.pageSize,this.pageNumber);
            let response=res.data;
            if(response.code===200){
                this.total=response.data.total;
                this.data=response.data.rows.map(item=>{
                    item.addTime=item.created.slice(0,16);
                    item.bannerName=item.name;
                    return item
                })
            }else{
                this.$Notice.error({
                    title: '请求出错',
                    desc:response.msg
                });
            }
            this.loading=false;
        },
        async saveForm(){
            const name=this.addBanner.name;
            const url=this.addBanner.link;
            const image_url =this.addBanner.src;
            const uuid =this.addBanner.uuid;
            // let reg=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
            const reg=/(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/ig;
            if(!name){
                this.$Notice.error({
                    desc:'请输入Banner名称'
                });
            }else if(!url){
                this.$Notice.error({
                    desc:'请输入链接地址'
                });
            }else if(!reg.test(url)){
                this.$Notice.error({
                    desc:'链接格式错误'
                })
            }else if(!image_url){
                this.$Notice.error({
                    desc:'图片不能为空'
                })
            }else if(this.canclick){
                this.canclick=false;
                let flag=this.addBanner.title==='新增Banner'?'save':'edit'
                let res=await saveBanner({name, url, image_url,uuid,flag });
                let response=res.data;
                if(response.code===200){
                    if(this.addBanner.title==='新增Banner'){
                        this.pageNumber=1;
                        this.getTable();
                    }
                    this.$Notice.success({
                        desc:'保存成功'
                    })
                    this.modal_banner=false;
                    this.getTable();
                }else{
                    this.$Notice.error({
                        title: '请求出错',
                        desc:response.msg
                    });
                }
                this.canclick=true;
            }
        },
        async goedit(obj){
            await this.qiniuToken();
            this.addBanner={
                uuid:obj.uuid,
                title:'编辑Banner',
                name:obj.name,
                link:obj.url,
                src:obj.image_url,
                bannerImg:{
                    name:'',
                    url:this.domain+obj.image_url,
                    status:'finished',
                    showProgress:true,
                    percentage:0
                }
            };
            this.modal_banner=true;
        },
        pageSizeChange(size){
        //回到第一页
            this.pageNumber=1;
            this.pageSize=size;
            this.getTable();
        },
        pageChange(number){
            this.pageNumber=number;
            this.getTable();
        },
        async handleAddbanner(){
            this.addBanner.title="新增Banner";
            await this.qiniuToken();
            this.modal_banner=true;
            
        },
        handleView(img){
            this.look_pic_wrap.look_pic=true;
            this.look_pic_wrap.src=img;

        },
        handleRemove(img){
            this.uploadList=[];
            this.addBanner.src='';
            this.addBanner.bannerImg={
                name:'',
                url:'',
                status:'',
                showProgress:true,
                percentage:0
            }
        },
        handleSuccess (res, file) {
            this.addBanner.src=res.hash;
            this.addBanner.bannerImg=file;
            this.addBanner.bannerImg.url=this.domain+res.hash;
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '图片格式错误',
                desc: '请选择 jpg 或 png 格式的图片'
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '图片过大',
                desc: '请选择文件大小小于2M的图片'
            });
        },
        handleBeforeUpload (file) {
            const check = this.$refs.upload.fileList.length < 2;
            if (!check) {
                this.$Notice.warning({
                    title: '一次只能上传一张'
                });
            }
            return check;
        }
    },
    watch:{
        modal_banner:function(){
            if(!this.modal_banner){
                this.addBanner={
                uuid:'',
                title:'',
                name:'',
                link:'',
                src:'',
                bannerImg:{
                    name:'',
                    url:'',
                    status:'',
                    showProgress:true,
                    percentage:0
                }
            }
            }
        }
    },
    created(){
        this.getTable();
        this.btnp=util.bpower(this,this.btn);
    }
}

</script>
<style lang='scss' >
.upload-wrap{
    text-align:center;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
}
.iconBox{
    display:inline-block;
    position:absolute;
    top:50%;
    left:50%;
   transform: translateX(-50%) translateY(-50%);

}
.upload-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
    i{
        color: #fff;
        font-size: 30px;
        cursor: pointer;
        margin: 0 10px;
    }
}
.upload-wrap:hover .upload-cover{
    display: block;
}
</style>